package edu.pku.sei.modeler.neditor.command;

import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;

import edu.pku.sei.modeler.model.core.MetaModelElement;
import edu.pku.sei.modeler.model.notation.core.NotationFactory;
import edu.pku.sei.modeler.model.notation.core.ShapeNode;
import edu.pku.sei.modeler.neditor.model.Diagram;

public class CreateNodeCommand extends Command {
	private MetaModelElement parent = null;
	private String typeID = null;
	private NotationFactory factory = null;
	static private Rectangle bound = new Rectangle(0,0,50,50);
	
	public CreateNodeCommand(){
		bound.setLocation(0, 0);
		bound.setSize(50, 50);
	}

	public void setFactory(NotationFactory factory) {
		this.factory = factory;
	}
	public void setLocation(Point location) {
		if(location==null) return;
		bound.setLocation(location);
	}
	public void setParent(MetaModelElement parent) {
		this.parent = parent;
	}
	public void setSize(Dimension size) {
		if(size==null) return;
		bound.setSize(size);
	}
	public void setTypeID(String typeID) {
		this.typeID = typeID;
	}

	@Override
	public boolean canExecute() {
		return true;
	}

	private ShapeNode node = null;
	
	@Override
	public void execute() {
		if(parent instanceof Diagram) {
			//ShapeNode 
			node = (ShapeNode)factory.createElement(typeID, true);
			node.setBound(bound);
			node.setModel(parent.getModel());
			
			((Diagram) parent).addNode(node);

		} else {
			//ShapeNode 
			node = (ShapeNode)factory.createElement(typeID, true);
			node.setModel(parent.getModel());
			
			((edu.pku.sei.modeler.model.notation.shape.Shape)parent).addSlaveWithInitBounds(node, bound);
		}
	}

	@Override
	public void redo() {
		// TODO Auto-generated method stub
		if(parent instanceof Diagram){
			factory.registerToPackage(node, typeID);
			((Diagram) parent).addNode(node);
		} else {
			factory.registerToPackage(node, typeID);
			((edu.pku.sei.modeler.model.notation.shape.Shape)parent).addSlaveWithInitBounds(node, bound);
		}
	}

	@Override
	public void undo() {
		// TODO Auto-generated method stub
		if(parent instanceof Diagram){
			((Diagram) parent).removeNode(node);
			factory.unRegisterFromPackage(node);
		}
		else {
			((edu.pku.sei.modeler.model.notation.shape.Shape)parent).removeSlave(node);
			factory.unRegisterFromPackage(node);
		}
	}
}
